package ArrayListDemo;

public class ArrayList {
    int size = 0;
    int capacity = 10;
    Integer[] arr = new Integer[capacity];

    public void add(int e, int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("非法");
        }

        if (size >= capacity) {
            int newCapacity = capacity + (capacity >> 1);
            Integer[] newArr = new Integer[newCapacity];
            System.arraycopy(arr, 0, newArr, 0, size);
            arr = newArr;
            capacity = newCapacity;
        }

        for (int i = size; i > index; i--) {
            arr[i] = arr[i - 1];
        }

        arr[index] = e;
        size++;
    }

    public Integer remove(int index) {
        Integer i1 = arr[index];
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("非法");
        }
        for (int i = index; i < size; i++) {
            arr[i] = arr[i + 1];
        }

        size--;
        return i1;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arr[i]).append(" ");
        }
        return sb.toString();
    }

//    public void print() {
//        for (int i = 0; i < size; i++) {
//            System.out.println(arr[i]);
//        }
//    }

    public Integer get(int index) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("非法");
        }
        return arr[index];
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add(1, 0);
        list.add(2, 1);

        Integer result = list.get(1);
        System.out.println(result);
        System.out.println(list.toString());
    }
}
